//
//  Checklist.swift
//  Checklists
//
//  Created by cygarm on 15/11/30.
//  Copyright © 2015年 Razeware. All rights reserved.
//

import UIKit

class Checklist: NSObject, NSCoding {
	var name = ""
	var items = [ChecklistItem]()
	var iconName: String
	
	convenience init(name: String) {
		self.init(name: name, iconName: "No Icon")
	}
	
	init(name: String, iconName: String) {
		self.name = name
		self.iconName = iconName
		super.init()
	}
	
	required init?(coder aDecoder: NSCoder) {
		name = aDecoder.decodeObjectForKey("Name") as! String
		items = aDecoder.decodeObjectForKey("Items") as! [ChecklistItem]
		iconName = aDecoder.decodeObjectForKey("IconName") as! String
		super.init()
	}
	
	func encodeWithCoder(aCoder: NSCoder) {
		aCoder.encodeObject(name, forKey: "Name")
		aCoder.encodeObject(items, forKey: "Items")
		aCoder.encodeObject(iconName, forKey: "IconName")
	}
	
	func countUncheckedItems() -> Int {
		#if false
		/*
		$0 is the running total,starts(initial) at zero
		$1 references a ChecklistItem object in the items array
		*/
		return items.reduce(0) { $0 + ($1.checked ? 0 : 1) }
		#else
		return items.reduce(0, combine: { (cnt, item) -> Int in
			cnt + (item.checked ? 0 : 1)
		})
		#endif
	}
	
	func sortTodoLists() {
		items.sortInPlace { (checklist1, checklist2) -> Bool in
			checklist1.dueDate.compare(checklist2.dueDate) == NSComparisonResult.OrderedAscending
		}
	}
}
